//
//  UserDynamicViewController.m
//  ChatDemo-UI2.0
//
//  Created by syun on 16/4/1.
//  Copyright © 2016年 syun. All rights reserved.
//

#import "UserDynamicViewController.h"
#import "FriendSysTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "DetailDynViewController.h"
#import "SYDetailDynamicViewController.h"
@interface UserDynamicViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView * tableView;
@end

@implementation UserDynamicViewController{
    
    
        BOOL canFlipOver;
        NSInteger pageno;
        NSMutableArray *dataArray;
        
        //背景图
        UIImageView *bgImageView;
        
        
        //头像
        XZHeaderImageView *headImageView;
        
        EmptyStateView *emptyView;//空状态

}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self getUserinfo];  //获得用户信息

    [self requestDataForTableview];
}

-(void)getUserinfo{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    [param setObject:@"api_user_getinfobyid" forKey:@"Method"];
    [param setObject:_userid forKey:@"userid"];
    
    [Utils get:nil parameters:param success:^(NSInteger recode, id jsonObject) {
        
        NSDictionary *dic = [jsonObject objectForKey:@"re_data"];
        NSDictionary *userinfoDic = [dic objectForKey:@"userinfo"];
        
        NSString *logo = [userinfoDic objectForKey:@"logo"];
        if (logo && ![logo hasPrefix:@"http"]) {
            logo = [NSString stringWithFormat:@"%@%@",REQUESTIMAGEURL,logo];
        }
        
        self.headUrl = logo;
        
        
        self.bgImageUrl = [[userinfoDic objectForKey:@"basepic"] stringValue];
        
        
        //测试环境
        //if (![bgImageUrl hasPrefix:@"http"]) {
        
        if ([self.bgImageUrl isEqualToString:@"0"]) {
//            self.bgImageUrl = @"https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1458264274&di=75597c9973c5572952d28f9f880defd2&src=http://file25.mafengwo.net/M00/00/84/wKgB4lYvUmeAWxYLAAu-KKvEhO037.jpeg";
        }else{
            
            //正式环境
            self->_bgImageUrl = [NSString stringWithFormat:@"%@%@",IMAGEHOSTURL,self->_bgImageUrl];
            }
    
    
        [self.tableView reloadData];
        
    } failure:^(NSInteger recode, NSError *error) {
        
        
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithOriginalName:@"back"] style:UIBarButtonItemStyleDone target:self action:@selector(back:)];
    self.navigationItem.leftBarButtonItem = backItem;

    self.navBar.nav_titleLabel.text=@"个人动态";
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, SCREENHEIGH) style:UITableViewStylePlain];
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    self.tableView.showsVerticalScrollIndicator=NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.separatorColor = RGBACOLOR(200, 200, 200, 1);
    self.tableView.mj_header = [MJRefreshHeader headerWithRefreshingBlock:^{
        
        [self requestDataForTableview];
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        [self requestMoreDataForTableview];
        
    }];

    pageno = 1;
    dataArray = [[NSMutableArray alloc] initWithCapacity:0];
    
    emptyView = [[EmptyStateView alloc] initWithFrame:CGRectMake((SCREENWIDTH-120)/2, (SCREENHEIGH-110+210)/2-70, 120, 110) andBackImage:@"dynamic_empty" andBottomStr:@"暂无个人动态"];
    [self.tableView addSubview:emptyView];
    [self.view addSubview:self.tableView];
    // Do any additional setup after loading the view.
}
- (void)requestDataForTableview
{
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"api_info_listbyuser" forKey:@"method"];
    [dict setObject:@"20" forKey:@"pagesize"];
    [dict setObject:_userid forKey:@"createuserid"];
    [dict setObject:@"1" forKey:@"pageno"];
    [dict setObject:@"1" forKey:@"type"];
    
    [Utils get:nil parameters:dict success:^(NSInteger recode, id resposeJson){
        
        [self->dataArray removeAllObjects];
        
        NSDictionary *dict = (NSDictionary *)resposeJson;
        NSArray * array = [dict objectForKey:@"re_data"];
        if ([array count] == 0) {
            
            [self->emptyView showEmptyImage];
            [self.tableView.mj_header endRefreshing];
            self.tableView.tableFooterView = [[UIView alloc]init];
            [self.tableView reloadData];
            return ;
            
        }else if (array.count == 20)
        {
            self->canFlipOver = YES;
        
        }else
        {
            self->canFlipOver = NO;
        }
        
        [self->emptyView hideEmptyImage];
        
        self->pageno = 2;

        [self->dataArray addObjectsFromArray:array];
        [self.tableView.mj_header endRefreshing];
        [self.tableView reloadData];
        
    } failure:^(NSInteger recode, NSError * error){
        
    }];
}

- (void)requestMoreDataForTableview
{
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"api_info_listbyuser" forKey:@"method"];
    [dict setObject:@"20" forKey:@"pagesize"];
    [dict setObject:_userid forKey:@"createuserid"];
    [dict setObject:[NSString stringWithFormat:@"%ld",(long)pageno] forKey:@"pageno"];
    [dict setObject:@"1" forKey:@"type"];
    
    [Utils get:nil parameters:dict success:^(NSInteger recode, id resposeJson){
        
        NSDictionary *dict = (NSDictionary *)resposeJson;
        NSArray * array = [dict objectForKey:@"re_data"];

        if(array.count == 20)
        {
            self->pageno ++;
            self->canFlipOver = YES;
        }else
        {
            self->canFlipOver = NO;
        }

        
     [self->dataArray addObjectsFromArray:array];
     [self.tableView.mj_footer endRefreshing];
     [self.tableView reloadData];
     
     } failure:^(NSInteger recode, NSError * error){
         
     }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 210;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, SCREENWIDTH, 180);
    
    bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 180)];

    bgImageView.contentMode = UIViewContentModeScaleAspectFill;
    bgImageView.clipsToBounds = YES;
    
    [bgImageView sd_setImageWithURL:[NSURL URLWithString:self.bgImageUrl] placeholderImage:[UIImage imageNamed:@"m_top_img"]];
    
    
    UILabel *nameLabel=[[UILabel alloc]initWithFrame:CGRectMake(10, 150, [UIScreen mainScreen].bounds.size.width-110, 30)];
    nameLabel.textAlignment=NSTextAlignmentRight;
    nameLabel.text=self.nickName;
    nameLabel.font=[UIFont boldSystemFontOfSize:16];
    nameLabel.textColor=[UIColor whiteColor];
    
    headImageView = [[XZHeaderImageView alloc] initWithFrame:CGRectMake(SCREENWIDTH - 90, 150, 60, 60)];
    
    
    [headImageView.headImage sd_setImageWithURL:[NSURL URLWithString:self.headUrl]];
    
    headImageView.clipsToBounds = YES;
    headImageView.layer.cornerRadius = 30;

    headImageView.contentMode = UIViewContentModeScaleAspectFill;
    
    [headerView addSubview:bgImageView];
    [headerView addSubview:headImageView];
    [headerView addSubview:nameLabel];
    
    return headerView;
}

//获取头像上的名称
-(NSString *)getNameOfImage:(NSString *)UserID
{
    NSDictionary *nameofimg=[[NSUserDefaults standardUserDefaults]objectForKey:@"user_nameOfImage"];
    NSString *name;
    if ([nameofimg.allKeys count]>0) {
        for (int h=0; h<[nameofimg.allKeys count];h++) {
            if ([UserID isEqualToString:[nameofimg.allKeys objectAtIndex:h]]) {
                name=[nameofimg objectForKey:UserID];
                nickLabel.hidden=NO;
                nickLabel.text=name;
            }
        }
    }else
    {
        nickLabel.hidden=YES;
    }
    
    return  name;
}
#pragma mark - UITableviewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

        NSDictionary *dict = [dataArray objectAtIndex:indexPath.row];
        NSString * fileidsStr = [dict objectForKey:@"fileid"];
        
        NSInteger line = 0;
        
        
        NSArray *fileids;
        
        if (fileidsStr.length != 0) {
            
            fileids = [fileidsStr componentsSeparatedByString:@","];
        }
        
        
        if ([fileids count]%3 == 0) {
            line = [fileids count]/3;
        }else
        {
            line = [fileids count]/3 + 1;
        }
    return  (75 + 12.5) *line + [self resizeContenLabelHeightWithSting:[dict objectForKey:@"scontent"]] + 55;

    
}
#pragma mark - UITableviewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [dataArray count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

        static NSString *sysNoticeIdentifier=@"sysNotice";
        FriendSysNoticeTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:sysNoticeIdentifier];
        if (cell == nil) {
            
            cell = [[FriendSysNoticeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:sysNoticeIdentifier];
        }
        
        [cell.contentView addSubview:cell.headImage];
        
        
        //取出字典
        NSDictionary *dict = [dataArray objectAtIndex:indexPath.row];
        
        [cell upDateCellWithDic:dict];
        
        //头像
        NSString *imagePath = [dict objectForKey:@"logo"];
        
        if (![imagePath hasPrefix:@"http"]) {
            
            imagePath = [NSString stringWithFormat:@"%@%@",REQUESTIMAGEURL,imagePath];
        }
        
        [cell.headImage.headImage sd_setImageWithURL:[NSURL URLWithString:imagePath]];
        //头像昵称
        NSString *username = [dict objectForKey:@"username"];
        
        if (username.length > 2) {
            username = [username substringFromIndex:username.length-2];
        }
        //头像类型
        int logoType = [[dict objectForKey:@"logotype"] intValue];
        cell.headImage.flag = logoType == 1?YES:NO;
        cell.headImage.namelabel.font = [UIFont systemFontOfSize:14];
        cell.headImage.namelabel.text = username;

        //选择属性为无
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
        
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    FriendSysNoticeTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//    DetailDynViewController *detailVC = [[DetailDynViewController alloc] init];
//    detailVC.cell = cell;
//    detailVC.infoid = [[dataArray objectAtIndex:indexPath.row] objectForKey:@"infoid"];
//    detailVC.flag=@"gerenfaxian";
//    detailVC.dUserId=self.userid;
//    detailVC.classId=[[dataArray objectAtIndex:indexPath.row] objectForKey:@"classid"];
//    CGFloat height = [self tableView:tableView heightForRowAtIndexPath:indexPath];
//    
//    //第二个cell的高度
//    detailVC.cellHeight = height;
//    [self.navigationController pushViewController:detailVC animated:YES];
    
//    if (![_userid isEqualToString:USERID]) {
//        
//        return;
//    }
    
    SYDetailDynamicViewController *detailVC = [[SYDetailDynamicViewController alloc] init];
    
    NSString *infoid = [[[dataArray objectAtIndex:indexPath.row] objectForKey:@"infoid"] stringValue];
    if (!infoid || infoid.length == 0){
        
        TTAlert(@"没有找到infoid");
        return;
    }
    
    detailVC.infoid = infoid;
    
    [self.navigationController pushViewController:detailVC animated:YES];
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (canFlipOver == NO) {
        
        UIView *view =[[ UIView alloc] initWithFrame:CGRectMake(0, self.tableView.contentSize.height, VIEW_WIDTH, 60)];
        
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 0.4)];
        lineView.backgroundColor = RGBACOLOR(222, 223, 229, 1);
        
        UILabel *label=[[UILabel alloc]init];
        label.frame= CGRectMake(0, 0.4, VIEW_WIDTH, 59.6);
        
        label.text = @"没有更多内容了";
        label.font = [UIFont boldSystemFontOfSize:14];
        label.textAlignment = NSTextAlignmentCenter;
        
        [label addSubview:lineView];
        
        [view addSubview:label];
        label.textColor = [UIColor colorWithHexString:@"979797"];
        self.tableView.tableFooterView = view;
        self.tableView.mj_footer = nil;
        
    }else if (canFlipOver == YES){
        
        self.tableView.tableFooterView = nil;
        
        self.tableView.mj_footer =[MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            
            [self requestMoreDataForTableview];
            
        }];
    }
    //end of loading //for example [activityIndicator stopAnimating]; }}
}
#pragma mark -- other
- (CGFloat)resizeContenLabelHeightWithSting:(NSString *)text
{
    if (text.length == 0) {
        return 0;
    }
    UIFont *font = [UIFont systemFontOfSize:14];
    
    //NSStringDrawingOptions opts = NSStringDrawingUsesLineFragmentOrigin |
    //NSStringDrawingUsesFontLeading;
    
    NSStringDrawingOptions opts = NSStringDrawingUsesLineFragmentOrigin;
    
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    [style setLineBreakMode:NSLineBreakByCharWrapping];
    
    NSDictionary *attributes = @{ NSFontAttributeName : font/*, NSParagraphStyleAttributeName : style */};
    
    CGSize maxSize = CGSizeMake(SCREENWIDTH - 15 - 65, CGFLOAT_MAX);
    CGSize size = [text boundingRectWithSize:maxSize
                                     options:opts
                                  attributes:attributes
                                     context:nil].size;
    return size.height;
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    
//    [super scrollViewDidScroll:scrollView];
   
    CGFloat sectionHeaderHeight = 210;
    
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        
    }
}

-(void)back:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}


@end
